package com.jx.service.system;

import com.jx.common.exception.ServiceException;
import com.jx.pojo.entity.system.User;
import com.jx.pojo.model.system.LoginUser;
import com.jx.pojo.po.system.LoginPO;
import com.jx.pojo.po.system.UserInfo;
import com.jx.pojo.vo.system.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
@Slf4j
public class LoginService {

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    /**
     * 用户登录
     */
    public LoginPO login(LoginVO loginVO) {

        // 校验账号密码
        User user = userService.getUserByAccount(loginVO.getAccount());
        if (user == null || !user.getPassword().equals(loginVO.getPassword())) {
            throw new ServiceException("账号或密码不存在");
        }

        // 生成token
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());
        loginUser.setUserKey(UUID.randomUUID().toString());
        loginUser.setUser(user);
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(1000L * 60 * 60 * 24 * 7);
        String token = tokenService.createToken(loginUser);

        // 用户信息
        UserInfo userInfo = new UserInfo(user.getId(), user.getUsername());
        return new LoginPO(token, userInfo);
    }

    /**
     * 用户退出
     */
    public void logout(HttpServletRequest request) {
        tokenService.delUserCache(request);
    }
}
